﻿using Networks.Handlers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Networks
{
    public class CallbackFactory
    {
        public const string ROUTE_KEY_NAME = "__r_";

        private static Dictionary<string, Action<JObject>> _callbacks = new Dictionary<string, Action<JObject>>();
        public static Dictionary<string, Action<JObject>> Callbacks { get => _callbacks; }

        /// <summary>
        /// 注册各种 回调
        /// </summary>
        public static void RegistCallbacks()
        {
            registCallback(Routes.CONNECTOR_LOGIN, ConnectorHandler.onRespLogin);

            registCallback(Routes.LOBBY_CHAT_SEND, GameHandler.onRespSendChat);

            registCallback(Routes.ROOM_LIST, GameHandler.onRespRoomList);
            registCallback(Routes.ROOM_CREATE, GameHandler.onRespCreateRoom);
            registCallback(Routes.ROOM_JOIN, GameHandler.onRespJoinRoom);
            registCallback(Routes.ROOM_LEAVE, GameHandler.onRespLeaveRoom);
            registCallback(Routes.ROOM_PLAYER_ACTION, GameHandler.onRespPlayerAction);

            registCallback(Routes.C2S_GAME_START, GameHandler.onRespStartGame);
        }

        private static void registCallback(string route, Action<JObject> handler)
        {
            if (_callbacks.ContainsKey(route))
            {
                // 已注册过同名的
                Debug.LogError("already exist route: " + route);
                return;
            }
            _callbacks.Add(route, handler);
        }

        /// <summary>
        /// 执行 回调
        /// </summary>
        /// <param name="route"></param>
        /// <param name="data"></param>
        public static void InvokeHandle(string route, JObject data)
        {
            Action<JObject> handler;
            _callbacks.TryGetValue(route, out handler);
            if (handler != null)
            {
                handler(data);
            }
            else
            {
                Debug.LogWarning("cannot find handler for " + route);
            }
        }
    }
}